package com.thinta.wind.ui.home.repository

import androidx.lifecycle.ViewModel
import androidx.paging.*
import com.thinta.wind.base.ViewModelFactory
import com.thinta.wind.entity.HotDataBean
import com.thinta.wind.entity.HotDataItemBean
import com.thinta.wind.network.RetrofitManager
import com.thinta.wind.ui.home.viewmodel.HotComViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.IOException

/*********************************************************
 * 版权信息：2021/7/2 15:13北京振中电子技术有限公司版权所有<p>
 * 创建作者：Wind<p>
 * 创建日期：2021/7/2 15:13<p>
 * *******************************************************<p>
 * 更新历史：    作者      日期      更新摘要<p>
 * <p>
 * *******************************************************<p>
 * 类功能说明：<p>
 */

class HotComRepository{

    suspend fun getHotData(catid : String, pageNum: String, pageSize : Int, userId : String) : HotDataBean? = withContext(Dispatchers.IO){
        val hotList = RetrofitManager.apiService.getHotList(catid, pageNum, pageSize, userId)
        hotList.data
    }

}

class HotComFactory(private val repository: HotComRepository) : ViewModelFactory() {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel?> create(modelClass: Class<T>): T = HotComViewModel(repository) as T

}


class NearByDataSource(private val repository: HotComRepository,
                       private val catId : String,
                       private val pageSize : Int,
                       private val userId : String) : PagingSource<Int, HotDataItemBean>(){

    override fun getRefreshKey(state: PagingState<Int, HotDataItemBean>): Int? {
        return state.anchorPosition
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, HotDataItemBean> {
        return try {
            val page = params.key ?: 1
            val dataList = repository.getHotData(catId, page.toString(), pageSize, userId)
            LoadResult.Page(
                data = dataList!!.list,
                prevKey = null,
                nextKey = if(dataList.hasNextPage) page + 1 else null
            )
        }catch (e : IOException){
            return LoadResult.Error(e)
        }catch (e : HttpException){
            return LoadResult.Error(e)
        }

    }

}

